import React, { Component } from 'react'

class StudentList extends Component {

  rmStudent = (index, ev) => {
    ev.preventDefault()
    if ( window.confirm('确定删除?') ) {
       this.props.removeStudent(index)
    }
  }

  render () {
    const { studentList } = this.props
    let totalAge = 0
    let avgAge = 0
    studentList.forEach(student => {
      totalAge += Number(student.age)
    }) 
    // 计算平均值
    avgAge = Math.floor(totalAge / studentList.length)
    console.log(studentList)
    return (
      <div>
        <table className="table table-striped">
          <thead>
            <tr>
              <td>学号</td>
              <td>姓名</td>
              <td>性别</td>
              <td>年龄</td>
              <td>爱好</td>
              <td>所属学院</td>
              <td>操作</td>
            </tr>
          </thead>
          <tbody>
            {
              studentList.map(student => {
                return (
                  <tr key={student.number}>
                    <td>{student.number}</td>
                    <td>{student.name}</td>
                    <td>{student.sex}</td>
                    <td>{student.age}</td>
                    <td>{student.hobbies.map((hobby, index) => <span key={index}>{hobby}</span>)}</td>
                    <td>{student.collage}</td>
                    <td>
                      <a href='#' onClick={ (ev) => { this.rmStudent(`${student.number}`, ev) }}>删除</a>
                      &nbsp;
                      <a href=''>修改</a>
                    </td>
                  </tr>
                )
              })
            }
          </tbody>
        </table>
        {studentList.length > 0 ? '' : '无学生信息'}
        <p>总共有{studentList.length}个学生</p>
        <p>学生的平均年龄是:{avgAge}</p>
      </div>
    );
  }
}

export default StudentList;
